package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import service.PutCache;
import service.Util;

import model.News;
import model.NewsRecent;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class DetailServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setCharacterEncoding("utf-8");
		String path = ((HttpServletRequest)req).getRequestURI();
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 

        resp.setHeader( "Cache-Control", "public, max-age=14400");
		resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
        
        if(count != 2)
        {
        	try {
				req.getRequestDispatcher("/404error.jsp").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
        	return;
        }
        
		// skip one token /question/abcd (remove sites)
		st.nextToken();
		String title_url = st.nextToken();
		
		if(title_url!=null)
		{
			try {
				ObjectifyService.register(News.class);
			} catch (Exception e) {
				// TODO: handle exception
			}
			Objectify objectify = ObjectifyService.begin();
			try {
				News news = objectify.get(new Key<News>(News.class, title_url));
				
				req.setAttribute("news", news);
				
				ArrayList<NewsRecent> newLess = PutCache.getCacheNews("newLess"+news.getAlias());
				if(newLess.size()<=0)
				{
					Query<News> list = objectify.query(News.class).filter("date < ", news.getDate()).filter("categoryAlias", news.getCategoryAlias()).order("-date").limit(10);
					ArrayList<News> arrayList = Util.convertArrayList(list);
					
					for(int i=(arrayList.size()-1);i>=0;i--)
					{
						NewsRecent newsRecent = new NewsRecent();
						newsRecent.setTitle(arrayList.get(i).getTitle().getValue());
						
						PutCache.putCacheNews(newsRecent, "newLess"+news.getAlias(), 10);
					}
				}
				
				ArrayList<NewsRecent> oldLess = PutCache.getCacheNews("oldLess"+news.getAlias());
				
				if(oldLess.size()<=0)
				{
					Query<News> list1 = objectify.query(News.class).filter("date > ", news.getDate()).filter("categoryAlias", news.getCategoryAlias()).order("-date").limit(10);
					ArrayList<News> arrayList = Util.convertArrayList(list1);
					
					for(int i=(arrayList.size()-1);i>=0;i--)
					{
						NewsRecent newsRecent = new NewsRecent();
						newsRecent.setTitle(arrayList.get(i).getTitle().getValue());
						
						PutCache.putCacheNews(newsRecent, "oldLess"+news.getAlias(), 10);
					}
				}				
				
				
				NewsRecent newsRecent = new NewsRecent();
				newsRecent.setTitle(news.getTitle().getValue());
				newsRecent.setThumb(news.getThumb());
				newsRecent.setDate(news.getDate());
				
				PutCache.putCacheNews(newsRecent, "newRecent", 15);
				
				PutCache.putCacheList(news.getCategoryAlias(), "category", 10);
			} catch (Exception e) {
				//resp.sendError(resp.SC_NOT_FOUND,"404 not found !");
			}
		}
		
		try {
			req.getRequestDispatcher("/detail.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
